package kr.pfg.applications.captureyourscreen.nativemenu
{
	import flash.display.NativeMenu;
	import flash.display.NativeMenuItem;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.ui.Keyboard;
	
	import kr.pfg.applications.captureyourscreen.events.NativeMenuEvent;
	
	public class CreateNativeMenuItem extends NativeMenu
	{
		public function CreateNativeMenuItem( xml: XML )
		{
			super();
			if( xml ) makeMenu( this, xml.children() );
		}
		private function makeMenu( menu: NativeMenu, xmlList: XMLList ): NativeMenuItem
		{
			var subMenu: NativeMenu;
			var menuItem: NativeMenuItem;
			for each( var xml: XML in xmlList )
			{
				if( String( xml.@label ).length > 0 )
				{
					menuItem = new NativeMenuItem( xml.@label );
					menuItem.name = xml.name();
					if( String( xml.@key ) ) 
					{
						menuItem.keyEquivalent = String( xml.@key );
						menuItem.keyEquivalentModifiers = [ Keyboard.CONTROL ];
					}
					menuItemEvent( menuItem );				
				}
				else
				{
					//if( String( xml.@separator ) ) ( String( xml.@separator ) == "true" ) ? isLine = true : isLine = false;
					menuItem = new NativeMenuItem( xml.name() );
					menuItem.name = xml.name();
					menuItemEvent( menuItem );
				}
				menu.addItem( menuItem );
				if( xml.children().length() > 0 )
				{
					menuItem.submenu = new NativeMenu();
					makeMenu( menuItem.submenu, xml.children() );
				}
			}
			return menuItem;
		}
		private function menuItemEvent( menuItem: NativeMenuItem ): void
		{
			menuItem.addEventListener( Event.SELECT, onSelectHandler );
		}
		private function onSelectHandler( e: Event ): void
		{
			var item: NativeMenuItem = e.target as NativeMenuItem;
			this.dispatchEvent( new NativeMenuEvent( NativeMenuEvent.MENU_SELECT, item ) );
		}
	}
}